<template>
  <el-dialog v-if="load" title="调整优先级" v-model="visible" append-to-body :close-on-click-modal="false" :z-index="2000" width="500px" @close="handleClose">
    <div class="grid grid-cols-2 gap-x-3 mt-2 mb-3">
      <VText title="系统模块" :value="form.model_id_name" />
      <VText title="原因类型" :value="form.reason_type_name" />
    </div>
    <VueDraggable v-model="list" target=".sort-target" animation="150" class="mb-2">
      <div class="grid grid-cols-5 border-t border-l">
        <div class="border-b border-r p-2 col-span-3">原因名称</div>
        <div class="border-b border-r p-2">优先级</div>
        <div class="border-b border-r p-2">操作</div>
      </div>
      <div class="sort-target border-l">
        <div v-for="(d, i) in list" :key="i" class="grid grid-cols-5">
          <div class="border-b border-r p-2 col-span-3">{{d.name}}</div>
          <div class="border-b border-r p-2 flex items-center">{{i+1}}</div>
          <div class="border-b border-r p-2 cursor-move flex items-center"><i class="dk-iconfont icon-Switch" /></div>
        </div>
      </div>
    </VueDraggable>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { ElMessage } from 'element-plus'
import { VueDraggable } from 'vue-draggable-plus'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const form = ref({})
const list = ref([
  {
    name: 'Joao',
    id: 1
  },
  {
    name: 'Jean',
    id: 2
  },
  {
    name: 'Johanna',
    id: 3
  },
  {
    name: 'Juan',
    id: 4
  }
])

// 打开弹窗
const open = async (selection) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  form.value = selection[0]
  loadings = reactive({})
  visible.value = true
  const {model_id, reason_type} = form.value
  api.levelInfo({model_id, reason_type}).then(res => {
    list.value = res.data
  })
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
// 提交
const submit = () => {
  loadings.submit = true
  api.updateLevel({reasons: list.value.map((d, i) => ({rc_id: d.rc_id, level: i+1}))}).then(res => {
    ElMessage.success('操作成功')
    emit('success')
    close()
  }).finally(() => {
    loadings.submit = false
  })
}

defineExpose({ open })
</script>